$(document).ready(function() {
    // Obtém as VCDs que são dadas como entrada
    var vcds = new Array(),
            countVCDS = 0;
    $("input[id=vcd]").each(function() {
        if (!_.isEmpty($(this).val())) {
            vcds.push($(this).val());
            countVCDS++;
        }
    });

    // TESTE
    var arrays = new Object(),
            number = 0;
    arrays[0] = ["A", "B", "C"];
    arrays[1] = ["D", "E", "F"];

    $.each(arrays, function(key, array) {
        if (key === "" + number + "") {
            var value = "C";
            removeItem(array, value);
            //console.log(array);
        }
    });

    // Cria novos Filtros //
    // oculta e exibe os campos para criar os filtros
    $('#filter-query').hide();
    $('a[id=create-filters]').click(function(evt) {
        createSelectForm(strCreateFilter);
        $('#filter-query').show();
        evt.preventDefault();
    });

    // Cria os options no select do Filter
    var inputFilter = $("input[id=input-filter-query]"),
            objectTextSelect = new Object();
    
    function createSelectForm(responseText) {
        var select = $("select[name=select-filter-query]"),
                option = $("<option value=\"default\"></option>"),
                arrayTextSelect = new Array();

        select.empty();
        inputFilter.empty();
        select.append(option);
        $.each(responseText, function(key, value) {
            for (var i = 0; i < value.length; i++) {
                option = $("<option name=\"filter-query\">").val(key).text(value[i]);
                arrayTextSelect.push(value[i]);
                select.append(option);
            }
        });
        objectTextSelect[countClicked] = arrayTextSelect;
    }

    // Pega os valores dos Filters
    var jsonTextQuery;
    function createFilter() {
        var arrayKey = new Array(),
                arrayValue = new Array();

        $("option[name=filter-query]:selected").each(function() {
            var value = $(this).attr("value");
            var text = $(this).text();
            arrayKey.push(value + " ?:" + text);
        });

        $("input[id=input-filter-query]").each(function() {
            var input = $(this).val();
            arrayValue.push(input.replace(/\"/g, '\''));
        });
        jsonTextQuery = JSON.stringify(generatingArrayQuery(arrayKey, arrayValue));

        return jsonTextQuery;
    }

    // Submeti os filtros criados para reconstruir a query
    var objectSelect = "";
    $("input[name=submit-filter]").on("click", function(evt) {
        getValueClicked();
        objectSelect = oldSelectOptions();
        evt.preventDefault();
    });

    // Adiciona os dados ao Array() no qual será utilizados para construir o filter na query.
    function generatingArrayQuery(arrayKey, arrayValue) {
        var mapKeysQuery = new Object(),
                mapValuesQuery = new Array(),
                arrayLength;

        (arrayKey.length > arrayValue.length) ? arrayLength = arrayKey.length : arrayLength = arrayValue.length;

        for (var i = 0; i < arrayLength; i++) {
            if (!_.isEmpty(arrayKey[i]) && !_.isEmpty(arrayValue[i])) {
                if (mapKeysQuery[arrayKey[i]] && $.inArray(arrayValue[i], mapKeysQuery[arrayKey[i]]) === -1 || mapKeysQuery[arrayKey[i]] && $.inArray(arrayValue[i], mapKeysQuery[arrayKey[i]]) !== -1) {
                    // Verifica se já existe a chave vinda do "key" e se o valor de "value" está presente no array.
                    if (mapKeysQuery[arrayKey[i]].indexOf(arrayValue[i]) === -1) {
                        mapKeysQuery[arrayKey[i]].push(arrayValue[i]);
                    }
                }
                else {
                    // Cria o array de acordo com o valor da "key" e adiciona o valor de "value".
                    mapKeysQuery[arrayKey[i]] = new Object();
                    mapValuesQuery = new Array();
                    mapValuesQuery.push(arrayValue[i]);
                    mapKeysQuery[arrayKey[i]] = mapValuesQuery;
                }
            }
        }
        return mapKeysQuery;
    }

    // Carrega a query para ser visualizada pelo usuário
    var countClicked = 0,
            arrayValueClick = new Array();
    arrayValueClick[0] = "";
    if (vcds.length > 0) {
        getValueClicked();
    }

    // Pega o valor do elemento clicado na tabela que exibi o resultado da VCD
    var title,
            tableID;
    $(".content").on("click", "#tablesorter a", function(evt) {
        if (countClicked < countVCDS - 1) {
            title = $(this).attr("title");
            tableID = $(this).attr("id");
            countClicked++;
            arrayValueClick.push(title);
            $('#filter-query').hide();
            getValueClicked();
        }
        evt.preventDefault();
    });

    // Reconstrói o select, cujo algum filtro foi criado
    var jsonTextOptions;
    function oldSelectOptions() {
        $.each(JSON.parse(createFilter()), function(key, value) {
            for (var i = 0; i < value.length; i++) {
                var values = key + " ?:" + value[i];
                jsonTextOptions = reconstructsSelect(countClicked, values);
            }
        });
        return jsonTextOptions;
    }

    // Adiciona os dados ao Array() no qual serão utilizados para reconstruir os options do select.
    var mapKeysQuery = new Object(),
            mapValuesQuery = new Array();
    function reconstructsSelect(key, value) {
        if (mapKeysQuery[key] && $.inArray(value, mapKeysQuery[key]) === -1 || mapKeysQuery[key] && $.inArray(value, mapKeysQuery[key]) !== -1) {
            // Verifica se já existe a chave vinda do "key" e se o valor de "value" está presente no array.
            if (mapKeysQuery[key].indexOf(value) === -1) {
                mapKeysQuery[key].push(value);
            }
        }
        else {
            // Cria o array de acordo com o valor da "key" e adiciona o valor de "value".
            mapKeysQuery[key] = new Object();
            mapValuesQuery = new Array();
            mapValuesQuery.push(value);
            mapKeysQuery[key] = mapValuesQuery;
        }
        return mapKeysQuery;
    }

    // Recria os filtros que já haviam sido criados anteriormente
    function arrowSelectPrevious(countClicked) {
        var list = objectSelect[countClicked];
        if (!_.isEmpty(list)) {
            var arrayOptions = objectTextSelect["" + countClicked + ""];
            var ol = $("ol")
                    .attr("id", "filter-sparql");

            var button = $("<input type=\"button\">")
                    .attr("id", "filter-sparql")
                    .attr("name", "query")
                    .attr("class", "buttonAdd");

            var buttonDel = $("<input type=\"button\">")
                    .attr("id", "filter-sparql")
                    .attr("name", "query")
                    .attr("class", "buttonDelete");

            ol.empty();
            for (var i = 0; i < list.length; i++) {
                var values = list[i].split(" ?:");

                var li = $("<li class=\"clone\">")
                        .text("Filter");

                var select = $("<select>")
                        .attr("id", "select-filter-query")
                        .attr("name", "select-filter-query");

                var optionNull = $("<option>")
                        .val("default");

                var input = $("<input type=\"text\">")
                        .attr("id", "input-filter-query")
                        .attr("name", "input-filter-query")
                        .attr("size", "40");

                select.append(optionNull.attr('selected', false));
                for (var j = 0; j < arrayOptions.length; j++) {
                    var option = $("<option>")
                            .attr("name", "filter-query");
                    if (arrayOptions[j] === values[1]) {
                        option.val(values[0])
                                .text(values[1])
                                .attr('selected', true);
                    } else {
                        option.val(values[0])
                                .text(arrayOptions[j])
                                .attr('selected', false);
                    }
                    select.append(option);
                }

                input.val(values[2]);

                li.append(select)
                        .append(input);

                if (i === 0) {
                    li.append(button);
                } else {
                    li.append(buttonDel)
                            .removeClass('clone');
                }
                ol.append(li);
            }
            $("div[id=filter-query]").append(ol);
            $('div[id=filter-query]').show();
        }
    }

    function removeValueSelect() {

    }

    // Remove filtros do Object()
    $('ol').on('click', '.buttonDelete', function() {
        var li = $(this).parent();
        var select = li.find('select');
        var selectVal = select.val();
        var selecLabel = select.find('option:selected').text();
        var inputValue = li.find('input[type="text"]').val();
        var formKey = selectVal + " ?:" + selecLabel;

        console.log(JSON.parse(createFilter()));

        $.each(JSON.parse(createFilter()), function(key, value) {
            if (key === formKey) {
                console.log("ANTES: " + value);
                removeItem(value, inputValue);
                console.log("DEPOIS: " + value);
            }
        });
    });

    // Retorna ao resultado da VCD anterior
    $(".pathVCD").on("click", "a", function(evt) {
        if (countClicked > 0) {
            removeItem(arrayValueClick, arrayValueClick[countClicked]);
            countClicked--;
            arrowSelectPrevious(countClicked);
            getValueClicked();
            evt.preventDefault();
        }
    });

    // Exibe quais dados serão visualizados quando a próxima VCD for executada
    function varsNextVCD(responseText) {
        var vars = "";
        for (var i = 0; i < responseText.length; i++) {
            if (i < responseText.length - 1) {
                vars += responseText[i] + " &raquo; ";
            } else {
                vars += responseText[i];
            }
        }

        if (countClicked > 0) {
            $(".pathVCD").html("<a href=\"#\" id=\"returnVCD\">Back</a> " + vars);
        } else {
            $(".pathVCD").html(vars);
        }
    }

    // Function para remover itens de um array
    function removeItem(array, value) {
        for (var i in array) {
            if (array[i] === value) {
                array.splice(i, 1);
                break;
            }
        }
    }

    // Pega o ID da linha da tabela que contém a tag <a></a>
    function findTableID() {
        $("#tablesorter").find("a").each(function() {
            tableID = $(this).attr("id");
        });
        return tableID;
    }

    // Quando algum valor é clicado esta função executa a VCD correspondente 
    var strCreateFilter;
    function getValueClicked() {
        $(".content").html("<b>Please wait...</b>&nbsp;&nbsp;<img src=\"./images/ajax-loader.gif\"/>");
        $.ajax({
            url: "execute-vcd",
            type: "GET",
            data: {
                "vcdss[]": vcds,
                valueClick: arrayValueClick[countClicked],
                tableID: tableID,
                countClick: countClicked,
                jsonTextQuery: createFilter()
            },
            dataType: "json",
            error: function(responseText) {
                console.log("ERRO: " + responseText);
            },
            success: function(responseText) {
                createTableJson(responseText[0], responseText[1]);
                varsNextVCD(responseText[2]);
                strCreateFilter = responseText[3];

                $(".pathVCD").show();
            }
        });
    }

    // Cria a tabela responsável por apresentar os resultados das VCDS
    function createTableJson(Results, Parameters) {
        $(".content").html("");

        var table = $("<table cellspacing=\"1\" id=\"tablesorter\" class=\"display\">"),
                thead = $("<thead>"),
                rowsTHead = $("<tr>"),
                tbody = $("<tbody>"),
                varsQuery = [];

        // Cabeçalho da tabela
        var heads = Results.head.vars,
                sizeHeads = heads.length;
        for (var i = 0; i < sizeHeads; i++) {
            varsQuery.push(heads[i]);
            rowsTHead.append($("<th>").html(heads[i]));
        }
        thead.append(rowsTHead);

        // Corpo da tabela
        var bodys = Results.results.bindings,
                sizeBodys = bodys.length,
                sizeVarsQuery = varsQuery.length;
        for (var i = 0; i < sizeBodys; i++) {
            var rowsTBody = $("<tr>"),
                    values = bodys[i];

            for (var j = 0; j < sizeVarsQuery; j++) {
                var tdBody = $("<td>");
                for (var k = 0; k < Parameters.length; k++) {
                    if (bodys[i].hasOwnProperty(varsQuery[j]) && varsQuery[j].toLowerCase() === Parameters[k].toLowerCase()) {
                        tdBody.html("<a href=\"#\" id=\"" + varsQuery[j] + "\" title=\"" + values[varsQuery[j]].value + "\">" + values[varsQuery[j]].value + "</a>");
                    } else if (bodys[i].hasOwnProperty(varsQuery[j])) {
                        tdBody.html(values[varsQuery[j]].value);
                    } else {
                        tdBody.html("");
                    }
                }
                rowsTBody.append(tdBody);
            }
            tbody.append(rowsTBody);
        }
        table.append(thead).append(tbody);

        $(".content").html(table);

        return $("#tablesorter").dataTable({
            "bPaginate": true,
            "bJQueryUI": false,
            "sPaginationType": "full_numbers",
            "bDestroy": true
        });
    }
});

